<!--
 * @description:
 * @param:
 * @return:
 * @author: Seven
-->
<template>
  <a-drawer v-model:visible="visible" :title="model.id ? '工单详情' : '新增工单'" placement="right" :width="450">
    <a-modal v-model:visible="showModal" title="选择退回人" @ok="handleOk">
      <span style="margin-left: 20px">退回人：</span>
      <a-select v-model:value="assignTo" allowClear placeholder="请选择" style="width: 200px; margin: 20px 0">
        <template v-for="(item, index) in userList" :key="index">
          <a-select-option :value="item.username">
            {{ item.realname }}
          </a-select-option>
        </template>
      </a-select>
    </a-modal>
    <a-form ref="formRef" :model="model" :rules="rules" :label-col="{ span: 5 }" @finish="onFinish">
      <a-form-item label="处理方式" name="handleType">
        <a-select v-model:value="model.handleType" allowClear placeholder="请选择处理方式" :disabled="isDisabled">
          <a-select-option :value="1">自主处理</a-select-option>
          <a-select-option :value="2">领导确认</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="工单类型" name="orderType">
        <a-select v-model:value="model.orderType" allowClear placeholder="请选择工单类型" :disabled="isDisabled">
          <template v-for="(item, index) in odrerTypeList" :key="index">
            <a-select-option :value="Number(item.value)">
              {{ item.label }}
            </a-select-option>
          </template>
        </a-select>
      </a-form-item>
      <a-form-item label="归属站点" name="stationCode">
        <a-select v-model:value="model.stationCode" allowClear :disabled="isDisabled">
          <template v-for="(item, index) in stationList" :key="index">
            <a-select-option :value="item.stationCode">
              {{ item.name }}
            </a-select-option>
          </template>
        </a-select>
      </a-form-item>
      <a-form-item label="工单内容" name="orderDetail">
        <a-textarea v-model:value="model.orderDetail" :rows="3" allowClear placeholder="请输入工单内容" :disabled="isDisabled" />
      </a-form-item>

      <template v-if="[1, 2, 3, '1', '2', '3'].includes(model.status)">
        <a-form-item label="处理描述" name="handleDescription">
          <a-input v-model:value="model.handleDescription" allowClear placeholder="请输入处理描述" :disabled="isDisabled" />
        </a-form-item>

        <a-form-item label="处理图片" name="handleAttachment">
          <template v-if="model.handleAttachment !== ''">
            <Image :src="model.handleAttachment" alt="" :width="100" />
          </template>
        </a-form-item>
      </template>

      <!-- <a-form-item label="处理人" name="assignTo">
        <a-select v-model:value="model.assignTo" allowClear placeholder="请选择处理人" :disabled="model.id">
          <template v-for="(item, index) in userList" :key="index">
            <a-select-option :value="item.username">
              {{ item.realname }}
            </a-select-option>
          </template>
        </a-select>
      </a-form-item> -->
      <a-form-item label="附件" name="attachments">
        <template v-if="isDisabled">
          <Image :src="model.attachments" :width="100" />
        </template>
        <template v-else>
          <a-upload
            name="file"
            :action="ossAction"
            :multiple="false"
            v-model:file-list="fileList"
            list-type="picture-card"
            :headers="tokenHeader"
            :showUploadList="true"
            :disabled="isDisabled"
            @change="handleUploadChange"
          >
            <template v-if="!isDisabled">
              <div class="flex items-center justify-end upload-form-item" title="点击上传文件">
                <i class="ico"></i>
                <span>上传</span>
              </div>
            </template>
          </a-upload>
        </template>
      </a-form-item>
      <a-form-item label="第三方维修" name="needRepair">
        <a-checkbox v-model:checked="model.needRepair" :disabled="model.status == '0' && roleCodes == 'FACTORY_OWNER' ? false : true" />
      </a-form-item>
      <template v-if="model.needRepair == 1">
        <a-form-item label="维修金额" name="repairePrice">
          <a-input
            v-model:value="model.repairePrice"
            :disabled="model.status == '0' && roleCodes == 'FACTORY_OWNER' ? false : true"
            type="number"
            :min="0"
          />
        </a-form-item>
        <a-form-item label="第三方单位" name="componyName">
          <a-input v-model:value="model.componyName" :disabled="model.status == '0' && roleCodes == 'FACTORY_OWNER' ? false : true" />
        </a-form-item>
        <a-form-item label="联系方式" name="componyTel">
          <a-input v-model:value="model.componyTel" :disabled="model.status == '0' && roleCodes == 'FACTORY_OWNER' ? false : true" />
        </a-form-item>
      </template>
      <a-form-item label="备注" name="remark">
        <a-input v-model:value="model.remark" allowClear placeholder="请输入备注" :disabled="isDisabled" />
      </a-form-item>
      <a-form-item label="操作">
        <a-button @click="resetForm" v-show="!isDisabled">重置</a-button>
        <a-divider type="vertical" v-show="!isDisabled" />
        <a-button type="primary" html-type="submit" v-show="!isDisabled">提交保存</a-button>

        <a @click="onAassgin()" v-show="model.status === '0'" v-auth="'order:assign'">分派</a>

        <template v-if="model.status === '1' && model.assignTo == username">
          <a @click="onSignback(1)">维修人员回退</a>
          <a-divider type="vertical" />
          <a @click="onRepair(2)">维修处理</a>
        </template>

        <template v-if="model.status == '2' && model.assignTo == username && roleCodes == 'FACTORY_OWNER'">
          <a @click="onRedo(record)">回退</a>
          <a-divider type="vertical" />
          <a @click="onAudit(record)">结算</a>
        </template>

        <!-- <a-button type="danger" v-show="model.id && model.status === '1'" @click="signbackOrder" v-auth="'order:signback'">退回</a-button>
        <a-divider type="vertical" v-show="model.id && model.status === '0' && username === model.assignTo" v-auth="'order:handle'" />
        <a-button type="primary" v-show="model.id && model.status === '0' && username === model.assignTo" @click="handleOrder" v-auth="'order:handle'"
          >处理</a-button
        >
        <a-divider type="vertical" v-show="model.id && model.status === '1' && username === model.assignTo" v-auth="'order:close'" />
        <a-button type="primary" v-show="model.id && model.status === '1' && username === model.assignTo" @click="auditOrder" v-auth="'order:close'"
          >结单</a-button
        > -->
        <!-- <a-divider type="vertical" v-show="model.id" v-auth="'order:handle'" />
        <a-button type="primary" v-show="model.id" @click="auditOrder">查看记录</a-button> -->
      </a-form-item>
    </a-form>
    <div></div>
    <!-- <a-timeline mode="right">
      <a-timeline-item>Create a services site 2015-09-01</a-timeline-item>
      <a-timeline-item>Solve initial network problems 2015-09-01</a-timeline-item>
      <a-timeline-item>Technical testing 2015-09-01</a-timeline-item>
      <a-timeline-item>Network problems being solved 2015-09-01</a-timeline-item>
    </a-timeline> -->
    <CommonAMap ref="commonAMap" @oks="getMapData" />

    <assginDialog ref="assginDialog" @oks="onDone" />

    <maintainDialog ref="maintainDialog" @oks="onDone" />
  </a-drawer>
</template>

<script lang="ts">
import { watch, ref, nextTick, defineComponent, getCurrentInstance, computed } from 'vue';
import { JDictSelectTag } from '/@/components/Form';
import {
  orderInfoApi,
  orderAddApi,
  orderModifyApi,
  confirmVistitApi,
  auditOrderApi,
  handleOrderApi,
  redoOrderApi,
  signbackOrderApi,
} from '/@/api/order';
import { projectListApi } from '@/api/project';
import CommonAMap from '/@/components/CommonAMap/index.vue';
import { useUserStore } from '/@/store/modules/user';
import { Modal, Empty, Image, message } from 'ant-design-vue';
import { json } from 'stream/consumers';
import { useGlobSetting } from '/@/hooks/setting';
import { getToken } from '/@/utils/auth';
import AssginDialog from './assgin-dialog.vue';
import MaintainDialog from './maintain-dialog.vue';
import { createVNode } from 'vue';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';

export default defineComponent({
  components: { JDictSelectTag, CommonAMap, MaintainDialog, AssginDialog, Image },
  props: {
    username: {
      type: String,
      default: '',
    },
    odrerTypeList: {
      type: Object,
      defalut: [],
    },
    userList: {
      type: Object,
      defalut: [],
    },
    stationList: {
      type: Object,
      defalut: [],
    },
  },
  setup(props, { emit }) {
    const userStore = useUserStore();
    let { proxy } = getCurrentInstance();
    const glob = useGlobSetting();
    const ossAction = computed(() => `${glob.uploadUrl}/sys/common/upload`);
    // 文件列表
    let fileList = ref([]);
    let showModal = ref(false);
    let assignTo = ref('');
    const tokenHeader = { 'X-Access-Token': getToken() };
    let visible = ref(false);
    let model = ref({
      stationCode: '',
      handleType: '',
      orderType: '',
      orderDetail: '',
      // assignTo: '',
      needRepair: 0,
      remark: '',
      attachments: '',
    });
    let roleCodes = ref('');
    let regionList = ref([]);
    let rules = ref({
      stationCode: [{ required: true, message: '请选择归属站点' }],
      handleType: [{ required: true, message: '请选择处理方式' }],
      orderType: [{ required: true, message: '请选择工单类型' }],
      orderDetail: [{ required: true, message: '请输入工单内容' }],
      attachments: [{ required: true, message: '请上传附件' }],
    });

    let projectList = ref([]);

    let isDisabled = computed(() => {
      if (model.value.id) {
        return true;
      } else {
        return false;
      }
    });

    function getRegionData(data: []) {
      regionList.value = data;
    }

    function signbackOrder() {
      assignTo.value = '';
      showModal.value = true;
      // signbackOrderApi({ orderId: model.value.id, assignTo: assignTo.value }).then((res) => {
      //   visible.value = false;
      //   message.success('操作成功');
      //   emit('oks');
      // });
    }
    function handleOk() {
      if (!assignTo.value) {
        message.error(`请选择回退人`);
        return;
      }
      showModal.value = false;
      signbackOrderApi({ orderId: model.value.id, assignTo: assignTo.value }).then((res) => {
        visible.value = false;
        message.success('操作成功');
        emit('oks');
      });
    }
    function auditOrder() {
      auditOrderApi({ orderId: model.value.id }).then((res) => {
        visible.value = false;
        message.success('操作成功');
        emit('oks');
      });
    }

    function handleOrder() {
      handleOrderApi({ orderId: model.value.id }).then((res) => {
        visible.value = false;
        message.success('操作成功');
        emit('oks');
      });
    }

    /**
     * 初始化数据
     * @param {number} id
     */
    function init(id) {
      orderInfoApi({ id }).then((res) => {
        res['state'] = res['state'] + '';
        res['alarmState'] = res['alarmState'] + '';
        model.value = { ...res };
      });
    }

    function resetForm() {
      proxy.$refs.formRef.resetFields();
    }

    /**
     * 初始化项目列表
     */
    function initProjectList() {
      projectListApi({}).then((res) => {
        projectList.value = res;
      });
    }

    function onFinish() {
      let { needRepair } = model.value;
      let data = {
        ...model.value,
        needRepair: needRepair ? 1 : 0,
      };
      orderAddApi(data).then((res) => {
        if (res) {
          proxy.$refs.formRef.resetFields();
          visible.value = false;
          message.success('新增成功');
          emit('oks');
        }
      });
      // data.needRepair = Number(data.needRepair);
      // if (!data['id']) {
      //   orderAddApi(data).then((res) => {
      //     proxy.$refs.formRef.resetFields();
      //     visible.value = false;
      //     message.success('新增成功');
      //     emit('oks');
      //   });
      // } else {
      //   orderModifyApi(data).then((res) => {
      //     proxy.$refs.formRef.resetFields();
      //     visible.value = false;
      //     message.success('修改成功');
      //     emit('oks');
      //   });
      // }
    }

    /**
     * 打开地图
     */
    function openMap() {
      proxy.$refs.commonAMap.visible = true;
      nextTick(() => {
        proxy.$refs.commonAMap.initMap(model.value);
      });
    }

    watch(
      () => visible.value,
      (v) => {
        if (v) {
          roleCodes.value = userStore.getUserInfo['roleCodes'];
          initProjectList();
        }
        if (!v) {
          model.value = {
            id: '',
            handleType: '',
            orderType: '',
            orderDetail: '',
            assignTo: '',
            needRepair: '',
            remark: '',
          };
          delete model.value.id;
          proxy.$refs.formRef.resetFields();
        }
      },
      { deep: true }
    );

    /**
     * 获取地图返回的经纬度
     */
    function getMapData({ longitue, latitude }) {
      Object.assign(model.value, {
        longitue,
        latitude,
      });
      AMap.plugin('AMap.Geocoder', () => {
        new AMap.Geocoder().getAddress([longitue, latitude], (status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            model.value.address = result.regeocode.formattedAddress;
          }
        });
      });
    }

    function showDrawer(data: {}) {
      visible.value = true;
      fileList.value = [];
      if (Object.keys(data).length == 0) {
        model.value.needRepair = false;
      }
      if (data) {
        model.value = JSON.parse(JSON.stringify(data));
        // model.value.needRepair = data.needRepair === 1;
        if (model.value.attachments) {
          fileList.value = model.value.attachments.split(',').reduce((acc, item) => {
            if (item) {
              acc.push({ url: item });
            }
            return acc;
          }, []);
        }
      }
    }

    function confirmorder() {
      confirmVistitApi({ id: model.value.id }).then((res) => {
        message.success('操作成功');
      });
    }
    /**
     * 上传成功后组将成文件列表
     */
    function handleUploadChange(e) {
      if (e.file.status == 'removed') {
        model.value.attachments = '';
      } else {
        if (e.file.response) {
          let fileName = e.file.response.message;
          const fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1);
          let url = `http://27.45.145.110:3200/api/${fileName}`;
          model.value.attachments = url;
          // fileList.value.push({
          //   name: fileName,
          //   url,
          //   type: `.${fileExtension}`,
          // });
        }
      }
    }

    function onAassgin() {
      proxy.$refs.assginDialog.visible = true;
      nextTick(() => {
        proxy.$refs.assginDialog.init({ orderId: model.value.id });
      });
    }

    function onSignback() {
      Modal.confirm({
        title: '提示',
        icon: createVNode(ExclamationCircleOutlined),
        content: '确定回退当前工单?',
        centered: true,
        onOk() {
          signbackOrderApi({ orderId: model.value.id }).then((res) => {
            message.success('退回成功');
            visible.value = false;
            emit('oks');
          });
        },
      });
    }

    function onRepair(idx) {
      proxy.$refs.maintainDialog.visible = true;
      nextTick(() => {
        proxy.$refs.maintainDialog.init({ orderId: model.value.id }, idx);
      });
    }

    /**
     * 厂长退回
     */
    function onRedo() {
      Modal.confirm({
        title: '提示',
        icon: createVNode(ExclamationCircleOutlined),
        content: '确定退回当前工单?',
        centered: true,
        onOk() {
          redoOrderApi({ orderId: model.value.id }).then((res) => {
            message.success('退回成功');
            visible.value = false;
            emit('oks');
          });
        },
      });
    }

    /**
     * 厂长结算
     */
    function onAudit() {
      Modal.confirm({
        title: '提示',
        icon: createVNode(ExclamationCircleOutlined),
        content: '确定结算当前工单?',
        centered: true,
        onOk() {
          auditOrderApi({ orderId: model.value.id }).then((res) => {
            message.success('结算成功');
            visible.value = false;
            emit('oks');
          });
        },
      });
    }

    function onDone() {
      visible.value = false;
      emit('oks');
    }

    return {
      init,
      visible,
      model,
      rules,
      projectList,
      regionList,
      ossAction,
      fileList,
      tokenHeader,
      showModal,
      assignTo,
      isDisabled,
      roleCodes,
      onAassgin,
      resetForm,
      onFinish,
      openMap,
      getMapData,
      getRegionData,
      showDrawer,
      confirmorder,
      auditOrder,
      handleOrder,
      handleUploadChange,
      signbackOrder,
      handleOk,
      onDone,
      onSignback,
      onRepair,
      onRedo,
      onAudit,
    };
  },
});
</script>
